package ink.metoo.fish.controller

import ink.metoo.fish.game.LiarTavernData
import ink.metoo.fish.game.LiarTavernGame
import org.springframework.beans.BeanUtils
import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("api/liar-tavern-game")
class LiarTavernGameController {

    data class LiarTavernGameModel(val uuid: String, val creator: String)
    
    fun LiarTavernData.toModel() = LiarTavernGameModel(uuid, creator)

    @GetMapping("play")
    fun play(@RequestParam player: String): LiarTavernGameModel {
        return LiarTavernGame.create(player).toModel()
    }

    @GetMapping("{uuid}/play")
    fun play(@RequestParam player: String, @PathVariable uuid: String): LiarTavernGameModel {
        return LiarTavernGame.join(uuid, player).toModel()
    }

    data class LiarTavernWatchModel(
        val lastVersion: Long,
        val events: List<LiarTavernData.GameEvent>,
        val playerDataList: List<LiarTavernData.PlayerData>
    )


    @GetMapping("{uuid}/watch")
    fun watch(
        @RequestParam player: String,
        @RequestParam version: Long,
        @PathVariable uuid: String
    ): LiarTavernWatchModel {
        val game = LiarTavernGame.getLiarTavernGame(uuid)
        val events = game.events
            .filter { it.version > version }
            .map {
                val target = it.copy()
                target.record = it.dataSelect(player)
                target
            }
        val model = LiarTavernWatchModel(
            events.lastOrNull()?.version ?: version,
            events,
            game.players.values.map {
                val target = LiarTavernData.PlayerData(it.name)
                BeanUtils.copyProperties(it, target, "items")
                if (player == it.name) {
                    target.items = it.items
                } else {
                    target.items = it.items.map { _ -> "?" }
                }
                target
            }.toList()
        )
        return model
    }

    @GetMapping("{uuid}/bang")
    fun bang(@RequestParam player: String, @PathVariable uuid: String) {
        LiarTavernGame.bang(uuid, player)
    }

    @GetMapping("{uuid}/cards")
    fun cards(@RequestParam player: String, @PathVariable uuid: String, @RequestParam use: Array<String>) {
        LiarTavernGame.cards(uuid, player, use)
    }


}
